#coding=utf-8
def openfile(filename):#读文件,用","分割
    daMat=[]
    data=open(filename)
    for line in data:
        line_data=line.split(',')
        daMat.append(line_data)
    return daMat

daMat=openfile('personaldata.txt')
# print daMat
import numpy as np
from numpy import *
def deal(daMat):
    '''
    处理文件
    1,将文件内容转换为float
    2,将X处理为该列的平均值
    '''
    data = []
    for i in range(daMat.__len__()):
        data_base=[]
        daMat_deal=daMat[i][3].split('.')
        del daMat[i][3]
        for j in range(daMat_deal.__len__()):
            if(daMat_deal[j]=='X'):
                daMat_deal[j]=0
            elif(daMat_deal[j]=='X\n'):
                daMat_deal[j] = 0
        data_base=map(float, daMat_deal)
        data.append(data_base)
    avg=mean(data,axis=0)
    for len in data:
        for j in range(len.__len__()):
            if(len[j]==0):
                    len[j]=avg[j]
    return_data=[]
    for len_daMat in daMat:
        len_data=map(float,len_daMat)
        return_data.append(len_data)
    for len_num in range(data.__len__()):
        for x in range(data[len_num].__len__()):
            return_data[len_num].append(data[len_num][x])
    return return_data
data=deal(daMat)
# print data

from sklearn.cluster import KMeans
from sklearn import metrics
'''
调用模型分类
'''
# kmeans_model1=KMeans(n_clusters=4).fit(data)
# print kmeans_model1.cluster_centers_
# print kmeans_model1.labels_

from scipy.spatial.distance import cdist
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
def elbow(daMat):
    #肘部法则判断
    font = FontProperties(fname=r"C:\\WINDOWS\\Fonts\\simsun.ttc", size=14)#C:\WINDOWS\Fonts
    K = range(1, 10)
    meandistortions = []
    for k in K:
        kmeans = KMeans(n_clusters=k)
        kmeans.fit(daMat)
        meandistortions.append(sum(np.min(cdist(daMat, kmeans.cluster_centers_, 'euclidean'), axis=1)) / daMat.__len__())
    plt.plot(K, meandistortions, 'bx-')
    plt.xlabel('k')
    plt.ylabel(u'平均畸变程度',fontproperties=font)
    plt.title(u'用肘部法则来确定最佳的K值',fontproperties=font);
    plt.show()
# elbow(data)







